package com.example.yiwei.crm.view.activity.JYCoordingActivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.managerDao;
import com.example.yiwei.crm.dao_impl.managerDaoImpl;
import com.example.yiwei.crm.entity.UserCarCustomerEntity;
import com.example.yiwei.crm.entity.managerEntity;
import com.example.yiwei.crm.json.ReasonJson;
import com.example.yiwei.crm.json.UseCarCustomerJson;
import com.example.yiwei.crm.util.AreaData;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.util.SC;
import com.example.yiwei.crm.view.Class.listviewClass.ListViewAllAdapter;
import com.example.yiwei.crm.view.Class.listviewClass.ListViewSelectAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class UseCarActivity extends AppCompatActivity {

    private Spinner health_spinner_manager,health_spinner_reason;
    private EditText number_use_car,address_use_car,beizhu_use_car,phone_use_car;
    private Button add_activity_btn_time,add_activity_btn_time2;
    private TextView add_activity_tv_time,add_activity_tv_time2,text_name,are;
    private TimePickerView mpv;
    private String time;
    private TimePickerView mpv1;
    private String time1;
    private SharedPreferences sp;
    private ImageView img_back,img_commit,img_address;
    private List<managerEntity> managerList;
    private ArrayAdapter adapter1,adapter2;
    private String managerName;
    private int manager_id;
    private List<String> name_list = new ArrayList<>();
    private PopupWindow mPopWindow;
    private ListView list_view_all,list_view_select;
    private Button select_btn;
    private EditText edit_select_customer;
    private Button select_btn_customer;
    private List<UserCarCustomerEntity> list_select,list_all,list_this;
    private ListViewAllAdapter adapter_all;
    private ListViewSelectAdapter adapter_select;
    private List<Map<String,String>> list_reason;
    private String ReasonID;
    private int state = 0;
    // 省数据集合
    private ArrayList<String> mListProvince = new ArrayList<String>();
    // 市数据集合
    private ArrayList<ArrayList<String>> mListCiry = new ArrayList<ArrayList<String>>();
    // 区数据集合
    private ArrayList<ArrayList<ArrayList<String>>> mListArea = new ArrayList<ArrayList<ArrayList<String>>>();
    // 省id数据集合
    private ArrayList<String> mListProvinceid = new ArrayList<String>();
    // 市id数据集合
    private ArrayList<ArrayList<String>> mListCiryid = new ArrayList<ArrayList<String>>();
    // 区id数据集合
    private ArrayList<ArrayList<ArrayList<String>>> mListAreaid = new ArrayList<ArrayList<ArrayList<String>>>();
    private OptionsPickerView<String> mOpv;
    //省id
    private String pid;
    private String cid;
    private String aid;
    //省名字
    private String pname;
    private String cname;
    private String aname;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_use_car);
        sp = getSharedPreferences("login", Context.MODE_PRIVATE);
        initView();
        list_select = new ArrayList<>();
        list_all = new ArrayList<>();
        list_this = new ArrayList<>();
        list_reason = new ArrayList<>();
        //创建选择器
        mpv = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        //设置时间范围
        Calendar calendar = Calendar.getInstance();
        mpv.setRange(calendar.get(Calendar.YEAR) - 100, calendar.get(Calendar.YEAR) + 100);
        //插入时间
        mpv.setTime(new Date());
        //选择监听
        mpv.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                time=getTime(date);
                add_activity_tv_time.setText(time);
            }
        });
        add_activity_btn_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mpv.show();
            }
        });
        mpv1 = new TimePickerView(this, TimePickerView.Type.HOURS_MINS);
        mpv1.setTime(new Date());
        mpv1.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                time1=getTime1(date);
                add_activity_tv_time2.setText(time1);
            }
        });
        add_activity_btn_time2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mpv1.show();
            }
        });
        initArea();
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                JSONObject object = sc.storage(sp);
                try {
                    object.put("admin", sp.getString("admin", null));
                    object.put("apphealth",1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = object.toString();
                managerDao manaDao = new managerDaoImpl();
                managerList = manaDao.queryAllManager(baseClass.query_manager_url, json);
                for (int i = 0; i < managerList.size(); i++) {
                    Log.d("aaa", managerList.get(i).toString());
                }
                for (int i2 = 0; i2 < managerList.size(); i2++) {
                    name_list.add(managerList.get(i2).getManager_name());
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter1 = new ArrayAdapter(UseCarActivity.this, R.layout.spinner_display_style, R.id.txtvwSpinner, name_list);
                        adapter1.setDropDownViewResource(R.layout.spinner_dropdown_style);
                        health_spinner_manager.setAdapter(adapter1);
                        health_spinner_manager.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                managerName = health_spinner_manager.getSelectedItem().toString();
                                for (int i1 = 0; i1 < managerList.size(); i1++) {
                                    if (managerName.equals(managerList.get(i1).getManager_name())) {
                                        manager_id = Integer.valueOf(managerList.get(i1).getManager_id());
                                    }
                                }

                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }

                        });
                    }
                });
            }
        }).start();
        img_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("".equals(phone_use_car.getText().toString())){
                    Toast.makeText(UseCarActivity.this, "请输入联系电话！！", Toast.LENGTH_SHORT).show();
                }else if ("".equals(add_activity_tv_time.getText().toString())||"".equals(add_activity_tv_time2.getText().toString())){
                    Toast.makeText(UseCarActivity.this, "请选择派车时间！！", Toast.LENGTH_SHORT).show();
                }else if ("".equals(address_use_car.getText().toString())){
                    Toast.makeText(UseCarActivity.this, "请输入目的地！！", Toast.LENGTH_SHORT).show();
                }else {
                    add();
                }
            }
        });

        select_btn_customer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list_select.clear();
                list_select.addAll(list_this);
                showPopupWindow();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = NetWorkUtils.getCount(baseClass.Find_Reason_URL,null);
                list_reason = ReasonJson.get(result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        List<String> list_sreason = new ArrayList<>();
                        for (int i = 0;i<list_reason.size();i++){
                            list_sreason.add(list_reason.get(i).get("CSK03"));
                        }
                        adapter2 = new ArrayAdapter(UseCarActivity.this, R.layout.spinner_display_style, R.id.txtvwSpinner, list_sreason);
                        adapter2.setDropDownViewResource(R.layout.spinner_dropdown_style);
                        health_spinner_reason.setAdapter(adapter2);
                        health_spinner_reason.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                ReasonID = list_reason.get(position).get("CSK01");
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                    }
                });
            }
        }).start();


    }
    private void initArea() {
        AreaData data = new AreaData(this);
        mListProvince = data.getListProvince();
        mListCiry = data.getListCiry();
        mListArea = data.getListArea();
        mListProvinceid = data.getListProvinceid();
        mListCiryid = data.getListCiryid();
        mListAreaid = data.getListAreaid();
        // 创建选项选择器对象
        mOpv = new OptionsPickerView<String>(this);

        // 设置标题
        mOpv.setTitle("选择城市");

        // 设置三级联动效果
        mOpv.setPicker(mListProvince, mListCiry, mListArea, true);

        // 设置是否循环滚动
        mOpv.setCyclic(false, false, false);

        // 设置默认选中的三级项目
        mOpv.setSelectOptions(0, 0, 0);

        // 监听确定选择按钮
        mOpv.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                // 返回的分别是三个级别的选中位置
                String tx = mListProvince.get(options1) + mListCiry.get(options1).get(option2) + mListArea.get(options1).get(option2).get(options3);
                pname = mListProvince.get(options1);
                cname = mListCiry.get(options1).get(option2);
                aname = mListArea.get(options1).get(option2).get(options3);
                pid = mListProvinceid.get(options1);
                cid = mListCiryid.get(options1).get(option2);
                aid = mListAreaid.get(options1).get(option2).get(options3);
                are.setText(tx);
            }
        });
        // 点击弹出选项选择器
        img_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOpv.show();
            }
        });
    }
    private void add() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SC sc = new SC();
                JSONObject object = sc.storage(sp);
                try {
                    object.put("UAB01",manager_id);
                    object.put("CSC04",managerName);
                    object.put("CSC05",add_activity_tv_time.getText().toString()+" "+add_activity_tv_time2.getText().toString()+":00");
                    Log.d("ddddd",add_activity_tv_time.getText().toString()+" "+add_activity_tv_time2.getText().toString()+":00");
                    object.put("CSC07",ReasonID);
                    object.put("CSC08",number_use_car.getText().toString());
                    object.put("CSC09",address_use_car.getText().toString());
                    object.put("REK01",beizhu_use_car.getText().toString());
                    object.put("CSC13",phone_use_car.getText().toString());
                    object.put("KAA23",pid);
                    object.put("KAA24",cid);
                    object.put("KAA25",aid);
                    object.put("KAA30",pname);
                    object.put("KAA31",cname);
                    object.put("KAA32",aname);
                    object.put("addoredit","add");
                    String json = object.toString();
                    final String result =  NetWorkUtils.getCount(baseClass.User_car_URL,json);
                    Log.d("result = ",result);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONObject object1 = new JSONObject(result);
                                if (object1.has("ifsuccess")){
                                    if ("true".equals(object1.getString("ifsuccess"))){
                                        Toast.makeText(UseCarActivity.this, "申请成功", Toast.LENGTH_SHORT).show();
                                        finish();
                                    }else {
                                        Toast.makeText(UseCarActivity.this, "申请失败，请稍后重试", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
    public static String getTime1(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(date);
    }

    private void initView() {
        health_spinner_manager = (Spinner) findViewById(R.id.health_spinner_manager);
        health_spinner_reason  = (Spinner) findViewById(R.id.health_spinner_reason);
        number_use_car = (EditText) findViewById(R.id.number_use_car);
        address_use_car = (EditText) findViewById(R.id.address_use_car);
        beizhu_use_car = (EditText) findViewById(R.id.beizhu_use_car);
        add_activity_btn_time = (Button) findViewById(R.id.add_activity_btn_time);
        add_activity_tv_time = (TextView) findViewById(R.id.add_activity_tv_time);
        img_back = (ImageView) findViewById(R.id.img_back);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        img_commit = (ImageView) findViewById(R.id.img_commit);
        add_activity_btn_time2 = (Button) findViewById(R.id.add_activity_btn_time2);
        add_activity_tv_time2 = (TextView) findViewById(R.id.add_activity_tv_time2);
        select_btn_customer = (Button) findViewById(R.id.select_btn_customer);
        text_name = (TextView) findViewById(R.id.text_name);
        phone_use_car = (EditText) findViewById(R.id.phone_use_car);
        are = (TextView) findViewById(R.id.are);
        img_address = (ImageView) findViewById(R.id.img_address);
    }
    private void showPopupWindow() {
        Button btn_up,btn_commit;
        View contentView = LayoutInflater.from(UseCarActivity.this).inflate(
                R.layout.popuwindow_select_coustomer, null);

        mPopWindow = new PopupWindow(contentView);
        mPopWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        mPopWindow.setHeight( LinearLayout.LayoutParams.MATCH_PARENT);

        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = contentView.getMeasuredWidth();    //  获取测量后的宽度
        final int popupHeight = contentView.getMeasuredHeight();  //获取测量后的高度
        int[] location = new int[2];
        edit_select_customer = (EditText) contentView.findViewById(R.id.edit_select_customer);
        select_btn = (Button) contentView.findViewById(R.id.select_btn);
        list_view_all = (ListView) contentView.findViewById(R.id.list_view_all);
        list_view_select = (ListView) contentView.findViewById(R.id.list_view_select);
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject object = new JSONObject();
                try {
                    object.put("UAB01",sp.getString("UAB01",null));
                    object.put("UAC05",sp.getString("UAC05",null));
                    object.put("UNT02",sp.getString("UNT02",null));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = object.toString();
                Log.d("ccccc",sp.getString("UAB01",null));
                Log.d("aaaaa",json);
                String result = NetWorkUtils.getCount(baseClass.Find_customer_all,json);
                Log.d("ccc",result);
                list_all = UseCarCustomerJson.get(result);
                Log.d("ddd",list_all.size()+"");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (list_all!=null){
                            adapter_all = new ListViewAllAdapter(list_all,UseCarActivity.this);
                            list_view_all.setAdapter(adapter_all);
                        }
                    }
                });
            }
        }).start();
        select_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject object = new JSONObject();
                        try {
                            object.put("UAB01",sp.getString("UAB01",null));
                            object.put("UAC05",sp.getString("UAC05",null));
                            object.put("UNT02",sp.getString("UNT02",null));
                            object.put("KAA02",edit_select_customer.getText().toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        String json = object.toString();
                        Log.d("ccccc",sp.getString("UAB01",null));
                        Log.d("aaaaa",json);
                        String result = NetWorkUtils.getCount(baseClass.Find_customer_all,json);
                        Log.d("ccc",result);
                        list_all = UseCarCustomerJson.get(result);
                        Log.d("ddd",list_all.size()+"");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (list_all!=null){
                                    adapter_all = new ListViewAllAdapter(list_all,UseCarActivity.this);
                                    list_view_all.setAdapter(adapter_all);
                                }
                            }
                        });
                    }
                }).start();
            }
        });
        adapter_select = new ListViewSelectAdapter(list_select,UseCarActivity.this);
        list_view_select.setAdapter(adapter_select);
        list_view_all.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d("点击了",position+"");
                for (int i = 0;i<list_select.size();i++){
                    if (list_all.get(position).getName().equals(list_select.get(i).getName())){
                        state = 1;
                    }
                }
                if (state==0){
                    list_select.add(list_all.get(position));
                    adapter_select.notifyDataSetChanged();
                }else {
                    Toast.makeText(UseCarActivity.this, "已选中此患者！！", Toast.LENGTH_SHORT).show();
                    state = 0;
                }

            }
        });
        list_view_select.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                list_select.remove(position);
                adapter_select.notifyDataSetChanged();
            }
        });
        btn_commit = (Button) contentView.findViewById(R.id.btn_commit);
        btn_up = (Button) contentView.findViewById(R.id.btn_up);
        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String result = "";
                for (int i = 0;i<list_select.size();i++){
                    if (i==0){
                        result = list_select.get(i).getName();
                    }else {
                        result = result+","+list_select.get(i).getName();
                    }
                }
                text_name.setText(result);
                list_this.clear();
                list_this.addAll(list_select);
                mPopWindow.dismiss();
            }
        });
        btn_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();
            }
        });
        select_btn_customer.getLocationOnScreen(location);
        mPopWindow.setAnimationStyle(R.style.contextMenuAnim);
        mPopWindow.setTouchable(true);
        mPopWindow.setOutsideTouchable(true);   //设置外部点击关闭ppw窗口
        mPopWindow.setFocusable(true);
        mPopWindow.update();
        mPopWindow.showAtLocation(contentView, Gravity.CENTER,0,0);
    }
}
